﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["loginoff"] == "loginoff")
        {
            BS_LoginUserID = null;
            Response.Redirect("~/Login.aspx");
        }
        if (Request.Form["account"] != null)
        {
            var account = Request.Form["account"];
            var password = Request.Form["password"];
            if (string.IsNullOrWhiteSpace(account))
            {
                ResponseMsg(false, "用戶名不能空");
                return;
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                ResponseMsg(false, "密码不能空");
                return;
            }
            CheckUserInfo(account.Trim(), password);
        }
    }

    private bool CheckUserInfo(string userName,string password)
    {
        DataSet ds = CommonLib.BLL.SYS_USER.CheckUserData(userName, password);
        DataRow userRow;
        if(ds.Tables.Count!=0 && ds.Tables[0].Rows.Count!=0)
            userRow = ds.Tables[0].Rows[0];
        else
        {
            ResponseMsg(false, "用户名不存在或密码不正确");
            return false;
        }
        if (userRow["user_id"].ToString() != userName || CommonLib.ComMon.StringCommon.StringDecode(userRow["user_password"].ToString()) != password)
            return false;
        BS_LoginUserID = userRow["user_id"].ToString();
        BS_LoginUserName = userRow["user_name"].ToString();
        BS_LoginDeptId = userRow["dept_id"].ToString();
        BS_LoginDeptName = userRow["dept_name"].ToString();
        BS_LoginDeptId = userRow["dept_id"].ToString();
        BS_LoginDeptIndex = Convert.ToInt32(userRow["dept_index"]);
        BS_PerStore= Convert.ToInt32(userRow["IS_MANAGER"].ToString());
        //上边代码加载用户基础信息
        //下边代码加载其他的
        DataTable roelsTb = CommonLib.BLL.BS_DATASET_SQL.SqlGetTable("select ROLE_ID from SYS_OPERATOR_ROLE a inner join SYS_DEPT_ROLES b on a.MASTER_ID = b.MASTER_ID where a.USER_ID = '"+BS_LoginUserID+"'");
        List<string> roels = new List<string>();
        foreach (DataRow row in roelsTb.Rows)
            roels.Add(row["ROLE_ID"].ToString());
        BS_LoginRoles = roels;

        //this.Session["g_sys_parameter"] = CommonLib.BLL.SYS_PARAMETER.GetList("1=1").Tables[0];

        ResponseMsg(true, "登陆成功");
        return true;
    }

    private void ResponseMsg(bool isLogin,string msg)
    {
        Response.Clear();
        Response.AddHeader("Content-Type", "application/json");
        string result = Newtonsoft.Json.JsonConvert.SerializeObject(new { result = isLogin, msg = msg }); 
        Response.Write(result);
        Response.End();
    }

}